package sysinit

import (
	"encoding/json"
	"errors"
	"fmt"
	"log"
	"os"

	"github.com/jinzhu/gorm"

	// _ "github.com/jinzhu/gorm/dialects/mysql"
	_ "github.com/jinzhu/gorm/dialects/postgres"
	// _ "github.com/jinzhu/gorm/dialects/sqlite3"
)

// DB 数据库
var DB *gorm.DB

// GORMLogger gorm sql日志
type GORMLogger struct {
	File *os.File
}

// Print gorm sql日志打印方法
func (l GORMLogger) Print(values ...interface{}) {
	logData := map[string]interface{}{
		"level":    values[0], // 操作级别
		"filePath": values[1], // 文件路径
		"time":     values[2], // 执行时间
		"sql":      values[3], // sql语句
		"params":   values[4], // 查询的参数
		"rows":     values[5], // 查询出来的数据条数
	}
	if jsonBytes, err := json.Marshal(logData); err != nil {
		log.Fatal(err)
	} else {
		if _, err := l.File.WriteString(string(jsonBytes) + "\n"); err != nil {
			log.Fatal(err)
		}
	}
}

// InitDB 初始化数据库连接
func InitDB() {
	var connection string
	switch Config.GetString("database.driver") {
	case "sqlite3":
		connection = fmt.Sprintf("%s.sqlite3.db", Config.GetString("database.name"))
	case "mysql":
		connection = fmt.Sprintf(
			"%s:%s@%s:%s/%s?charset=utf8&parseTime=True&loc=Local",
			Config.GetString("database.user"), Config.GetString("database.password"),
			Config.GetString("database.host"), Config.GetString("database.port"), Config.GetString("database.name"),
		)
	case "postgres":
		connection = fmt.Sprintf(
			"host=%s port=%s user=%s password=%s dbname=%s sslmode=disable",
			Config.GetString("database.host"), Config.GetString("database.port"),
			Config.GetString("database.user"), Config.GetString("database.password"), Config.GetString("database.name"),
		)
	default:
		log.Fatal(errors.New("unavailable database driver"))
	}
	DB, err := gorm.Open(Config.GetString("database.driver"), connection)
	if err != nil {
		log.Fatal(err)
	}
	// 设置GORM日志
	if Config.GetString("app.env") == "dev" {
		var logger GORMLogger
		logFile, err := os.OpenFile(Config.GetString("path.log")+"/sql.log", os.O_APPEND|os.O_CREATE, 0666)
		if err != nil {
			log.Fatal(err)
		}
		logger.File = logFile
		DB.LogMode(true)
		DB.SetLogger(logger)
	}
}
